package com.itheima.comtroller;

import com.itheima.pojo.Dept;
import com.itheima.utils.Result;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/7 23:28
 * @Desc:
 */
@RestController
@Slf4j
public class DeptController {
    @Autowired
    private DeptService deptService;

    //添加部门
    @RequestMapping(value = "/depts", method = RequestMethod.POST)
    public Result addDept(@RequestBody Dept dept) {
        boolean flag = deptService.addDept(dept.getName());

        return flag == true ? Result.success() : Result.error("部门名称不能为空或已存在");
    }

    //删除部门信息
    @RequestMapping(value = "/depts/{id}", method = RequestMethod.DELETE)
    public Result deleteDept(@PathVariable Integer id) {
        boolean flag = deptService.deleteDept(id);

        return flag == true ? Result.success() : Result.error("错误，部门信息不存在");
    }

    //修改部门信息
    @RequestMapping(value = "/depts", method = RequestMethod.PUT)
    public Result updateDept(@RequestBody Dept dept) {
        boolean flag = deptService.updateDept(dept.getId(), dept.getName());

        return flag == true ? Result.success() : Result.error("部门名称不能为空或该部门已存在");
    }

    //查询部门信息
    @RequestMapping(value = "/depts", method = RequestMethod.GET)
    public Result deptList() {
        List<Dept> depts = deptService.deptList();

        return depts.size() != 0 ? Result.success(depts) : Result.error("未查询到任何信息");
    }

    //根据id查询
    @RequestMapping(value = "/depts/{id}", method = RequestMethod.GET)
    public Result findDeptById(@PathVariable Integer id) {
        List<Dept> depts = deptService.findDeptById(id);

        return depts.size() != 0 ? Result.success(depts.get(0)) : Result.error("未查询到任何信息");
    }
}
